package ace.module.account.core.impl.service.impl;

import ace.module.account.core.impl.service.IamOauth2Service;
import ace.module.captcha.api.CaptchaApplicationApi;
import ace.module.captcha.api.CaptchaImageApi;
import ace.module.captcha.api.CaptchaItemApi;
import ace.module.captcha.api.model.dto.CaptchaApplicationDto;
import ace.module.captcha.api.model.dto.CaptchaImageDto;
import ace.module.captcha.api.model.dto.CaptchaItemDto;
import ace.module.captcha.api.model.input.CaptchaCreateInput;
import ace.module.common.core.impl.properties.ModuleCommonSecurityProperties;
import ace.module.common.core.impl.service.BasePropertiesService;
import ace.module.oauth2.server.api.Oauth2Api;
import ace.module.oauth2.server.api.model.dto.ext.Oauth2AccessTokenDto;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/3/18 16:16
 */
@Component
@AllArgsConstructor
public class IamOauth2ServiceImpl implements IamOauth2Service {

  private final Oauth2Api oauth2Api;
  private final CaptchaApplicationApi captchaApplicationApi;
  private final CaptchaImageApi captchaImageApi;
  private final CaptchaItemApi captchaItemApi;
  private final BasePropertiesService basePropertiesService;
  private final ModuleCommonSecurityProperties moduleCommonSecurityProperties;

  @Override
  public String getDefaultAdminAdministratorAccessTokenValue() {
    String basicAuthorization = basePropertiesService.getAdminOauth2ClientBasicAuthorization();
    String username = moduleCommonSecurityProperties.getAdministratorUsername();
    String password = moduleCommonSecurityProperties.getAdministratorPassword();
    CaptchaApplicationDto captchaApplicationDto = captchaApplicationApi.getAndCheckNotNullAdminApplication().check();
    CaptchaImageDto captchaImageDto = captchaImageApi.createBase64Data(
            CaptchaCreateInput.builder()
                .captchaAppId(captchaApplicationDto.getId())
                .build()
        )
        .check();

    CaptchaItemDto captchaItemDto = captchaItemApi.getById(captchaImageDto.getCaptchaItemId()).check();
    Oauth2AccessTokenDto oauth2AccessTokenDto = oauth2Api.getTokenByRestGrantTypeAndPasswordMethod(
        basicAuthorization,
        username,
        password,
        captchaItemDto.getId(),
        captchaItemDto.getCode()
    ).check();
    String accessTokenValue = oauth2AccessTokenDto.getAccessToken();
    return accessTokenValue;
  }

}
